<template>
  <div ref="dom"></div>
</template>

<script>
import echarts from 'echarts'
import { on, off } from '@/libs/tools'
export default {
  name: 'MulBar',
  props: {
    datas: Object,
    text: String,
    subtext: String
  },
  data () {
    return {
      dom: null
    }
  },
  methods: {
    resize () {
      this.dom.resize()
    },
    initChart () {
      let mySeries = []
      for (let i = 0; i < this.datas.legend.length; i++) {
        let item = {}
        item.name = this.datas.legend[i]
        item.type = 'bar'
        item.data = this.datas.yAxis[i]
        mySeries.push(item)
      }
      const option = {
        title: { text: this.text, x: 'center', textStyle: { fontSize: 16, color: '#516b91' } },
        color: this.datas.barColor || ['#a2c4c9', '#bf80ff', '#ffd966', '#9FE6B8'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true
            }
          }
        },
        calculable: true,
        legend: {
          data: this.datas.legend,
          top: '20',
          textStyle: { color: '#516b91' }
        },
        grid: {
          top: '20%',
          left: '1%',
          right: '3%',
          bottom: '2%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.datas.xAxis
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: this.datas.yName,
            axisLabel: {
              formatter: function (a) {
                a = +a
                return isFinite(a) ? echarts.format.addCommas(+a) : ''
              }
            }
          }
        ],
        series: mySeries
      }
      this.$nextTick(() => {
        this.dom = echarts.init(this.$refs.dom)
        this.dom.setOption(option)
        on(window, 'resize', this.resize)
      })
    }
  },
  mounted () {
    this.initChart()
  },
  beforeDestroy () {
    off(window, 'resize', this.resize)
  }
}
</script>
